package com.ad.payload.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

import static java.lang.System.currentTimeMillis;

/**
 * @author gdx
 * @since JDK 1.8
 */
@Service
@Component
public class JwtUtil {


//    @Value("${auth.jwt.secret}")
    private String secret = "F59BD65F7EDAFB087A81D4DCA06C4910";

//    @Value("${auth.jwt.expire}")
    private long expire = 36000;

    /**
     * @param token
     * @return
     */
    /*public JwtInfo getJwtInfoFromToken(String token) {
        Claims claims = parseJWT(token);
        JwtInfo jwtInfo = JSON.parseObject(JSON.toJSONString(claims), JwtInfo.class);

        return jwtInfo;
    }*/

    public Claims getJwtClaimsFromToken(String token){
        Claims claims = parseJWT(token);
        return claims;
    }

    public String getUserOpenIdFromToken(String token){
        Claims claims = parseJWT(token);
        return claims.get("userOpenId").toString();
    }

    /**
     *
     * @return
     */
    private SecretKey generalKey() {
        byte[] encodedKey = secret.getBytes();
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }


    /**
     *
     * @param jwt
     * @return
     */
    public Claims parseJWT(String jwt) {
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
        return claims;
    }

    /**
     * @ Author     ：zwb
     * @ Date       ：2020/6/8 9:51
     */
    public String createJWT(Map<String, Object> claims) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //Map<String, Object> claims = JSON.parseObject(JSON.toJSONString(jwtInfo), Map.class);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setSubject("userInfo")
                .setExpiration(generateExpirationDate())
                .signWith(signatureAlgorithm, key);

        return builder.compact();
    }

    /**
     * 生成token的过期时间
     */
    public Date generateExpirationDate() {
        return new Date(currentTimeMillis() + expire * 1000);
    }





}